package com.farewell.blog.config;

import com.farewell.blog.service.impl.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author Farewell
 * @date 2021/2/15
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService).passwordEncoder(new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return s.equals(charSequence.toString());
            }
        });
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 对静态资源放行
        web.ignoring().antMatchers("/js/**", "/css/**", "/img/**", "lib/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 设置拦截
        http.authorizeRequests()
                .antMatchers("/login", "/error/**", "/about/**", "/blog/**",
                        "/index/**", "/search/**", "/_fragments/**", "/types/**").permitAll()
                .antMatchers("/admin/**").hasAuthority("ROLE_ADMIN");
        // 管理退出
        http.csrf().disable()
                .logout()
                .logoutUrl("/logout");
        // 设置登录页位置及用户名密码对应的参数
        http.formLogin()
                .loginPage("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .loginProcessingUrl("/admin/login");

        // 退出
        http.logout().logoutSuccessUrl("/login");
    }
}
